<template>
  <view class="container">
    <map
        style="width: 100%; height: 300px;"
        :latitude="latitude"
        :longitude="longitude"
        :markers="markers"

        @click="onMapTap">
    </map>
    <uni-group mode="line" title="行程管理">
      <view>
        <view>
          <uni-section v-for="(item,index) in tripList" :title="item.tripIdWbxqy?.toString().padStart(8, '0')"
                       type="line">
            <uni-list :border="false">
              <uni-list-item :title="item.startLocationWbxqy" :note="'出发时间:'+item.startTimeWbxqy"/>
              <uni-list-item
                  :title="item.endLocationWbxqy"
                  :note="'到达时间:'+item.endTimeWbxqy?'到达时间: 未到达':item.endTimeWbxqy"
                  :rightText="getStatusText(item.tripStatusWbxqy)"
              />
              <button class="test"/>
            </uni-list>
          </uni-section>
        </view>
        <uni-card style="margin: 15px 0 0;">
          <view v-if="show" style="margin-top: 10px">
            <picker style="margin-bottom: 10px" mode="multiSelector" :range="locationData"
                    @change="handleMultiLocationChange('start', $event)"
                    @columnchange="handleColumnChange('start', $event)">
              <view>
                出发点: {{ startLocation }}
              </view>
            </picker>
            <picker style="margin-bottom: 10px" mode="multiSelector" :range="locationData"
                    @change="handleMultiLocationChange('end', $event)"
                    @columnchange="handleColumnChange('end', $event)">
              <view>
                目标点: {{ endLocation }}
              </view>
            </picker>
            <uni-datetime-picker type="datetime" @change="handleDateChange" :value="departureTime">
              <view class="picker">
                出发时间: {{ departureTimeDisplay }}
              </view>
            </uni-datetime-picker>
            <button @click="addTripButton" class="primary-button">添加行程</button>
          </view>
          <view v-else>
            用车结束/未批准 无法添加行程
          </view>
        </uni-card>
      </view>
    </uni-group>
  </view>
</template>

<script setup>
// --------------------------------添加行程--------------------------------
import {onMounted, ref} from 'vue'
import {addTrip, getTripList} from "../../api/tripMG";
import {onLoad} from '@dcloudio/uni-app';
// 行程列表
const tripList = ref([])
// 请求ID
const requestId = ref()
const show = ref()
onLoad((options) => {
  requestId.value = options.requestId
  show.value = options.showAdd === 'true'
});


const locationData = ref([
  ['北京市', '上海市', '广东省'], // 第一列省份数据
  ['北京市'], // 第二列市数据，根据选择的省份改变
  ['东城区', '西城区', '朝阳区'] // 第三列县数据，根据选择的市改变
]);
const startLocation = ref('');
const endLocation = ref('');
const departureTime = ref('');
const departureTimeDisplay = ref('');
const currentSelection = ref({
  start: [0, 0, 0], // 当前选中的省市县索引
  end: [0, 0, 0]
});

const handleMultiLocationChange = (type, event) => {
  const val = event.detail.value;
  currentSelection.value[type] = val;
  const selectedProvince = locationData.value[0][val[0]];
  const selectedCity = locationData.value[1][val[1]];
  const selectedCounty = locationData.value[2][val[2]];
  if (type === 'start') {
    startLocation.value = `${selectedProvince} ${selectedCity} ${selectedCounty}`;
  } else {
    endLocation.value = `${selectedProvince} ${selectedCity} ${selectedCounty}`;
  }
};

const handleColumnChange = (type, event) => {
  const column = event.detail.column;
  const value = event.detail.value;
  const data = {
    locationData: locationData.value,
    currentSelection: currentSelection.value[type]
  };

  switch (column) {
    case 0:
      // 修改省份，更新市和县数据
      data.currentSelection[0] = value;
      data.currentSelection[1] = 0;
      data.currentSelection[2] = 0;
      data.locationData[1] = getCities(value);
      data.locationData[2] = getCounties(value, 0);
      break;
    case 1:
      // 修改市，更新县数据
      data.currentSelection[1] = value;
      data.currentSelection[2] = 0;
      data.locationData[2] = getCounties(data.currentSelection[0], value);
      break;
    case 2:
      // 修改县
      data.currentSelection[2] = value;
      break;
  }

  locationData.value = data.locationData;
  currentSelection.value[type] = data.currentSelection;
};

const getCities = (provinceIndex) => {
  const cities = [
    ['北京市'],
    ['上海市'],
    ['广州市', '深圳市']
  ];
  return cities[provinceIndex];
};

const getCounties = (provinceIndex, cityIndex) => {
  const counties = [
    [
      ['东城区', '西城区', '朝阳区', '海淀区']
    ],
    [
      ['黄浦区', '徐汇区', '长宁区', '静安区']
    ],
    [
      ['越秀区', '荔湾区', '海珠区', '天河区'],
      ['罗湖区', '福田区', '南山区', '宝安区']
    ]
  ];
  return counties[provinceIndex][cityIndex];
};

const handleDateChange = (datetime) => {
  departureTime.value = datetime;
  departureTimeDisplay.value = datetime;
};

const addTripButton = async () => {
  // 添加行程的逻辑
  await addTrip({
    "requestIdWbxqy": requestId.value,
    "startLocationWbxqy": startLocation.value,
    "endLocationWbxqy": endLocation.value,
    "startTimeWbxqy": departureTime.value.replace(" ", "T")
  })
  uni.showToast({
    title: "新建行程成功!"
  })
  await fetchTripList()
};
const fetchTripList = async () => {
  tripList.value = await getTripList({
    requestId: requestId.value
  })
}
// testopen
const testOpen = async () => {
  console.log("test")
}
// 当加载时执行
onMounted(() => {
  fetchTripList()
})
// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'S':
      return '未开始'
    case 'I':
      return '进行中'
    case 'E':
      return '已结束'
    default:
      return '未知状态'
  }
}
// 地图
const latitude = ref(23.106574); // 纬度
const longitude = ref(113.324587); // 经度

const markers = ref([
  {
    id: 0,
    latitude: 23.13065,
    longitude: 113.3274,
    iconPath: '/static/marker.png',
    width: 20,
    height: 30,
    callout: {
      content: '天宝大厦',
      color: '#ffffff',
      fontSize: 14,
      borderRadius: 15,
      borderWidth: '10',
      bgColor: '#e51860',
      display: 'ALWAYS'
    }
  }
]);
const onMapTap = (e) => {
  console.log('地图被点击', e);
  const { latitude, longitude } = e.detail;
  // 在点击位置添加一个标记
  markers.value.push({
    id: markers.value.length, // 自动生成标记的 id
    latitude: latitude,
    longitude: longitude,
    width: 30,
    height: 30,
    iconPath: '/static//marker.png',
  });
}
</script>


<style scoped>
.container {
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  padding: 20px;
}

.test {
  all: unset;
  width: 100%;
  display: flex; /* 使用 flex 布局 */
  justify-content: flex-end; /* 将内容固定到右侧 */
  //background-color: red;
}

</style>
